<?php namespace App\Http\Controllers;

use App\Forum;
use App\ForumDiscuss;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Industry;
use App\Page;
use App\Plan;
use App\PlanJoin;
use App\PlanSetNum;
use App\Profession;
use App\ShareInfo;
use App\User;
use App\UserInfo;
use App\VisitLog;
use Faker\Provider\File;
use Illuminate\Contracts\Auth\Guard;
use Auth;
use Illuminate\Http\Request;

class AdminController extends Controller
{
    public function login(){
        return view('admin.login');
    }

    public function planList(){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $allPlan = Plan::orderBy('created_at','desc')->get();

        foreach($allPlan as $plan){
            /** @var Plan $plan */
            $hasJoinCount  = PlanJoin::wherePlanId($plan->id)->whereIsPay(1)->count();
            $hasJoinAmount = PlanJoin::wherePlanId($plan->id)->whereIsPay(1)->sum('amount');

            if(is_null($hasJoinAmount) || $hasJoinAmount == '')
                $hasJoinAmount = 0.00;

            $inventAmount = round((float)$plan->invent_num * (float)$plan->amount,2) + $hasJoinAmount;

            $plan->join_count  = $hasJoinCount;
            $plan->join_amount = $hasJoinAmount;
            $plan->invent_amount = $inventAmount;
        }

        $thatPlanSet = PlanSetNum::whereId(1)->first();

        return view('admin.plan-list',['plans'=>$allPlan,"plan_set"=>$thatPlanSet]);
    }

    public function planAdd(Request $request){
        $id = $request->get('id');

        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        /** @var Plan $thatPlan */
        $thatPlan = Plan::whereId($id)->first();

        return view('admin.plan-add',['plan'=>$thatPlan]);
    }

    public function memberList(Request $request){
        $planId = $request->get('plan_id');
        $isPay  = !is_null($request->get('is_pay'))?$request->get('is_pay'):1;

        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        /** @var Plan $thatPlan */
        $thatPlan = Plan::whereId($planId)->first();

        if(!$thatPlan){
            $planJoins = PlanJoin::whereIsPay($isPay)->orderBy('created_at','desc')->paginate(20);
        }else{
            $planJoins = PlanJoin::whereIsPay($isPay)->wherePlanId($thatPlan->id)->orderBy('created_at','desc')->paginate(20);

        }

        if(count($planJoins) > 0){
            foreach ($planJoins as $planJoin){
                /** @var PlanJoin $planJoin */
                $userinfo = UserInfo::whereUserId($planJoin->user_id)->first();
                $thePlan  = Plan::whereId($planJoin->plan_id)->first();
                $thatUser = User::whereId($planJoin->user_id)->first();

                $planJoin->userinfo = $userinfo;
                $planJoin->user     = $thatUser;
                $planJoin->plan     = $thePlan;
            }
        }

        $allPlans = Plan::orderBy('id','desc')->get();

        return view('admin.member-list',['plan_joins'=>$planJoins,'plans'=>$allPlans,'plan_id'=>$planId,'is_pay'=>$isPay]);
    }

    public function selectList(Request $request){
        $planId = $request->get('plan_id');

        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        /** @var Plan $thatPlan */
        $thatPlan = Plan::whereId($planId)->first();

        if(!$thatPlan){
            $planJoins = PlanJoin::whereIsSelect("1")->orderBy('created_at','desc')->get();
        }else{
            $planJoins = PlanJoin::whereIsSelect("1")->wherePlanId($thatPlan->id)->orderBy('created_at','desc')->get();

        }

        if(count($planJoins) > 0){
            foreach ($planJoins as $planJoin){
                /** @var PlanJoin $planJoin */
                $userinfo = UserInfo::whereUserId($planJoin->user_id)->first();
                $thePlan  = Plan::whereId($planJoin->plan_id)->first();
                $thatUser = User::whereId($planJoin->user_id)->first();

                $planJoin->userinfo = $userinfo;
                $planJoin->plan     = $thePlan;
                $planJoin->user     = $thatUser;
            }
        }

        $allPlans = Plan::orderBy('id','desc')->get();

        return view('admin.select-list',['plan_joins'=>$planJoins,'plans'=>$allPlans,'plan_id'=>$planId]);
    }

    public function pageManager(Request $request){
        $pages = Page::orderBy('created_at','desc')->get();

        return view('admin.page-manager',['pages'=>$pages]);
    }

    public function pageSet(Request $request){

        $id = $request->get('id');

        $thatPage = Page::whereId($id)->first();

        return view('admin.page-set',['page'=>$thatPage]);
    }

    public function dataShow(Request $request){
        $selectTime = $request->get('select_time');

        //获取昨天的最大时间和最小时间
        $yy = date('Y', strtotime('-1 days'));
        $ym = date('m', strtotime('-1 days'));
        $yd = date('d', strtotime('-1 days'));
        $yesterdayStartTime = mktime(0,0,0,$ym,$yd,$yy);
        $yesterdayEndTime   = mktime(23,59,59,$ym,$yd,$yy);

        //获取当天的最大时间和最小时间
        $ty = date('Y', time());
        $tm = date('m', time());
        $td = date('d', time());
        $todayStartTime = mktime(0,0,0,$tm,$td,$ty);
        $todayEndTime   = mktime(23,59,59,$tm,$td,$ty);

        //获取本月的第一天和最后一天
        $beginMonth = date('Y-m-01 00:00:00', strtotime(date("Y-m-d")));
        $endMonth   = date('Y-m-d 23:59:59', strtotime("$beginMonth +1 month -1 day"));

        //用户数据统计
        $todayNewUsersCount     = User::whereBetween('created_at',[date('Y-m-d H:i:s',$todayStartTime),date('Y-m-d H:i:s',$todayEndTime)])->count(); //今日新增用户
        $yesterdayNewUsersCount = User::whereBetween('created_at',[date('Y-m-d H:i:s',$yesterdayStartTime),date('Y-m-d H:i:s',$yesterdayEndTime)])->count(); //昨日新增用户
        $theMonthNewUsersCount  = User::whereBetween('created_at',[$beginMonth,$endMonth])->count();
        $allUsersCount          = User::count();

        //平台收入统计
        $todayOrderCount     = PlanJoin::whereIsPay(1)->whereBetween('created_at',[date('Y-m-d H:i:s',$todayStartTime),date('Y-m-d H:i:s',$todayEndTime)])->count(); //今日新增用户
        $yesterdayOrderCount = PlanJoin::whereIsPay(1)->whereBetween('created_at',[date('Y-m-d H:i:s',$yesterdayStartTime),date('Y-m-d H:i:s',$yesterdayEndTime)])->count(); //昨日新增用户
        $theMonthOrderCount  = PlanJoin::whereIsPay(1)->whereBetween('created_at',[$beginMonth,$endMonth])->count();
        $allOrderCount      = PlanJoin::whereIsPay(1)->count();

        $todayOrderSum     = PlanJoin::whereIsPay(1)->whereBetween('created_at',[date('Y-m-d H:i:s',$todayStartTime),date('Y-m-d H:i:s',$todayEndTime)])->sum('amount'); //今日新增用户
        $yesterdayOrderSum = PlanJoin::whereIsPay(1)->whereBetween('created_at',[date('Y-m-d H:i:s',$yesterdayStartTime),date('Y-m-d H:i:s',$yesterdayEndTime)])->sum('amount'); //昨日新增用户
        $theMonthOrderSum  = PlanJoin::whereIsPay(1)->whereBetween('created_at',[$beginMonth,$endMonth])->sum('amount');
        $allAmountSum      = PlanJoin::whereIsPay(1)->sum('amount');

        //性别比例显示
        $sexOne = UserInfo::whereSex(0)->count();
        $sexMan = UserInfo::whereSex(1)->count();
        $sexWon = UserInfo::whereSex(2)->count();

        $sexOneRatio = round($sexOne / $allUsersCount,2) * 100;
        $sexManRatio = round($sexMan / $allUsersCount,2) * 100;
        $sexWonRatio = round($sexWon / $allUsersCount,2) * 100;

        $hoursVisitNum = array();
        $selectDate = null;
        if(is_null($selectTime) || $selectTime == ''){
            $selectDate = date('Y-m-d',time());
        }else{
            $selectDate = $selectTime;
        }

        for($i=0;$i<=24;$i++){
            $startTime = strtotime($selectDate) + ($i * 3600);
            $endTime   = strtotime($selectDate) + (($i+1) * 3600) -1;
            $theHourCount = VisitLog::whereBetween('created_at',[date('Y-m-d H:i:s',$startTime),date('Y-m-d H:i:s',$endTime)])->count();
            array_push($hoursVisitNum,$theHourCount);
        }

        $oneHoursVisitNum = array();
        $theTime = date('Y-m-d H:i:s',time());
        for($i=0;$i<=59;$i++){
            $startTime = strtotime($theTime) - 3600 + ($i * 60);
            $endTime   = strtotime($theTime) - 3600 + (($i+1) * 60) - 1;

            $theHourCount = VisitLog::whereBetween('created_at',[date('Y-m-d H:i:s',$startTime),date('Y-m-d H:i:s',$endTime)])->count();
            $data['time'] = date('Y-m-d H:i:s',strtotime($theTime) - 3600 + (($i+1) * 60) - 1);
            $data['num']  = $theHourCount;
            array_push($oneHoursVisitNum,$data);
        }

        return view('admin.data-show',[
            'today_users_count'     => $todayNewUsersCount,
            'yesterday_users_count' => $yesterdayNewUsersCount,
            'mount_users_count'     => $theMonthNewUsersCount,
            'all_users_count'       => $allUsersCount,

            'today_order_count'     => $todayOrderCount,
            'yesterday_order_count' => $yesterdayOrderCount,
            'month_order_count'     => $theMonthOrderCount,
            'all_order_count'       => $allOrderCount,
            'today_order_sum'       => $todayOrderSum,
            'yesterday_order_sum'   => $yesterdayOrderSum,
            'month_order_sum'       => $theMonthOrderSum,
            'all_order_sum'         => $allAmountSum,

            'sex_one_ratio'         => $sexOneRatio,
            'sex_man_ratio'         => $sexManRatio,
            'sex_won_ratio'         => $sexWonRatio,

            'hour_nums'             => $hoursVisitNum,
            'one_hour_nums'         => $oneHoursVisitNum,
            'select_time'           => $selectTime
        ]);
    }

    public function setShareInfo(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $share = ShareInfo::wherePage("home")->first();

        return view("admin.share",["share"=>$share]);
    }

    public function functionList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $allFunctions = Profession::wherePid(0)->orderBy("id","desc")->get();

        if(count($allFunctions) > 0){
            foreach ($allFunctions as $function){
                /** @var Profession $function */
                $childs = Profession::wherePid($function->id)->get();
                $function->childs = $childs;
            }
        }

        return view("admin.function-list",["functions"=>$allFunctions]);
    }

    public function industryList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $allFunctions = Industry::wherePid(0)->orderBy("id","desc")->get();

        if(count($allFunctions) > 0){
            foreach ($allFunctions as $function){
                /** @var Profession $function */
                $childs = Industry::wherePid($function->id)->get();
                $function->childs = $childs;
            }
        }

        return view("admin.industry-list",["functions"=>$allFunctions]);
    }

    public function forumList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $forums = Forum::orderBy("id","desc")->get();

        if(!is_null($forums) && count($forums) > 0){
            foreach ($forums as $forum){
                $forum->img_url = FileManager::getImgFromOssUrl($forum->img_id);

                $userInfo = UserInfo::whereUserId($forum->user_id)->first();
                if($userInfo){
                    $userInfo->photo_url = $userInfo ? UserManager::getUserPhotoUrl($userInfo->photo_id) : null;
                }

                $forum->user_info = $userInfo ? $userInfo : null;

                $forumDiscussCount = ForumDiscuss::whereFId($forum->id)->count();
                $forum->discuss_count = $forumDiscussCount;
            }
        }

        return view("admin.forum-list",["forums"=>$forums]);
    }

    public function forumSet(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = $request->get("id");

        $thatForum = Forum::whereId($id)->first();

        if($thatForum){
            $thatForum->img_url = FileManager::getImgFromOssUrl($thatForum->img_id);
        }

        return view("admin.forum-set",["forum"=>$thatForum]);
    }

    public function forumDiscussList(Request $request){
        if(Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));

        $id = $request->get("id");

        $thatForum = Forum::whereId($id)->first();

        if(!$thatForum){
            return redirect(route('Admin.Home.forumList'));
        }

        $forumDiscussList = ForumDiscuss::whereFId($thatForum->id)->orderBy("id","desc")->get();
        if(count($forumDiscussList) > 0){
            foreach ($forumDiscussList as $forumDiscuss){

                $fromUserInfo = UserInfo::whereUserId($forumDiscuss->user_id)->first();

                if(!$fromUserInfo){

                    $forumDiscuss->photo_url = FileManager::getImgFromOssUrl($forumDiscuss->photo_id);
/*                        $forumDiscuss->from_user_info=$forumDiscuss->nick_name;*/
                        $forumDiscuss->from_uesr_nickname=$forumDiscuss->nick_name;

                }

                else{
                    $forumDiscuss->photo_url = UserManager::getUserPhotoUrl($fromUserInfo->photo_id);
/*                    $forumDiscuss->from_user_info = $fromUserInfo ? $fromUserInfo :null;*/
                    $forumDiscuss->from_uesr_nickname = $fromUserInfo ->nickname;

                }
            /*    if($fromUserInfo)$fromUserInfo->photo_url = UserManager::getUserPhotoUrl($fromUserInfo->photo_id);
                $forumDiscuss->from_user_info = $fromUserInfo ? $fromUserInfo : null;*/





                $toUserInfo = UserInfo::whereUserId($forumDiscuss->to_user_id)->first();
                if($toUserInfo)$toUserInfo->photo_url = UserManager::getUserPhotoUrl($toUserInfo->photo_id);
                $forumDiscuss->to_user_info = $toUserInfo ? $toUserInfo : null;
            }
        }

        return view("admin.forum-discuss-list",["forum"=>$thatForum,"forumDiscussList"=>$forumDiscussList]);
    }

    public function forumDiscussSet(Request $request)
    {

        if (Auth::guard('admin')->guest())
            return redirect(route('Admin.Home.login'));



        $forum_id=$request->get('forum_id');
        $id = is_null($request->get('id'))?$request->get('id'):0;


        $forum=Forum::whereId($forum_id)->first();



        return view('admin.forum-discuss-set',['forum'=>$forum]);
    }
}